#include <Windows.h>
#include <tchar.h>
#include <assert.h>
#include <time.h>

#define WAITMODE

extern HWND ghWnd;

void OnIdle(HWND hWnd)
{	
	if (NULL != hWnd)
	{
		srand((int)time(NULL));

		HDC hDC = GetDC(hWnd);
		HBRUSH hBrush = CreateSolidBrush(RGB(rand() % 256, rand() % 256, rand() % 256));

		RECT rtClient;
		GetClientRect(hWnd, &rtClient);	
		if (!IsRectEmpty(&rtClient))
		{
			int nWidth = rtClient.right - rtClient.left;
			int nHeight = rtClient.bottom - rtClient.top;

			RECT rtDraw;
			SetRect(&rtDraw, rand() % nWidth, rand() % nHeight, rand() % nWidth, rand() % nHeight);
		
			FillRect(hDC, &rtDraw, hBrush);
		}
		ReleaseDC(hWnd, hDC);
		DeleteObject((HBRUSH)hBrush);
	}

	return;
}

void MessageLoopForWaitMode()
{
	MSG Msg;
	while (GetMessage(&Msg, NULL, 0, 0))
	{	
		TranslateMessage(&Msg);
		DispatchMessage(&Msg);
	} 
}


void MessageLoopForNoWaitMode()
{
	MSG Msg;

	while (true)
	{	
		if (PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE))
		{
			if (WM_QUIT == Msg.message)
			{
				break;
			} 
			TranslateMessage(&Msg);
			DispatchMessage(&Msg);
		} else {
			OnIdle(ghWnd);
		}
	}
}

void MessageLoop()
{
#ifdef WAITMODE
	MessageLoopForWaitMode();
#else
	MessageLoopForNoWaitMode();
#endif

	return;
}

